package dataStructure;

/**
 * 稀疏数组
 * 一个二维数组中，大部分都是默认值，这时候就可以用稀疏数组保存
 */
public class SparseArray {
    public static void main(String[] args) {
        int[][] array = new int[10][11];
        array[0][3] = 1;
        array[1][7] = 2;
        array[5][6] = 3;
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 11; j++) {
                if (array[i][j] != 0) {
                    sum++;
                }
            }
        }
        int k = 1;
        //如果数组中有sum个值不是默认值，则sparseArray有sum+1行
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = 10;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        //二维数组转换成稀疏数组
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 11; j++) {
                if (array[i][j] != 0) {
                    sparseArray[k][0] = i;
                    sparseArray[k][1] = j;
                    sparseArray[k][2] = array[i][j];
                    k++;
                }
            }
        }


        //稀疏数组转换成二维数组
        int[][] result = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            result[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 11; j++) {
                System.out.print(array[i][j] + " ");
                if (j == 10) {
                    System.out.println();
                }
            }
        }
        System.out.println("*********************************");

        for (int i = 0; i < sum + 1; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(sparseArray[i][j] + " ");
                if (j == 2) {
                    System.out.println();
                }
            }
        }
        System.out.println("*******************************");
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 11; j++) {
                System.out.print(result[i][j] + " ");
                if (j == 10) {
                    System.out.println();
                }
            }
        }
    }
}
